#include "Stack.h"

void STInit(ST* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = ps->Top = 0;
}


void STDstroy(ST* ps)
{
	if (ps->arr)
	{
		free(ps->arr);
		ps->arr = NULL;
	}
	ps->capacity = ps->Top = 0;
}

void STPush(ST* ps, STDatatype x)
{
	assert(ps);
	if (ps->capacity == ps->Top)
	{
		int newcapacity = ps->capacity == 0 ? sizeof(STDatatype) : 2 * ps->capacity;
		STDatatype* ret = (STDatatype*)realloc(ps->arr, sizeof(STDatatype) * newcapacity);
		if (ret == NULL)
		{
			perror("realloc");
			return;
		}
		ps->capacity = newcapacity;
		ps->arr = ret;
	}
	ps->arr[ps->Top] = x;
	ps->Top++;
}

int STEmpty(ST* ps)
{
	assert(ps);
	return ps->Top == 0;
}

void STPop(ST* ps)
{
	assert(!STEmpty(ps));
	ps->Top--;
}


STDatatype StackTop(ST* ps)
{
	assert(ps);
	return ps->arr[ps->Top-1];
}
